package org.spiderflow.users.controller;

import org.apache.commons.lang3.StringUtils;
import org.spiderflow.common.ConstantCom;
import org.spiderflow.common.redis.userinfo.RedisUserInfoUtil;
import org.spiderflow.config.ResponseResult;
import org.spiderflow.config.RestResultGenerator;
import org.spiderflow.config.exception.ExecptionWhole;
import org.spiderflow.config.permission.PermissionCheck;
import org.spiderflow.config.permission.PermissionCodeEnum;
import org.spiderflow.file.bean.File;
import org.spiderflow.file.service.FileService;
import org.spiderflow.logs.entity.Logs;
import org.spiderflow.logs.service.LogsService;
import org.spiderflow.users.entity.Users;
import org.spiderflow.users.entity.UsersUpdate;
import org.spiderflow.users.service.UsersService;
import org.spiderflow.utils.DataUtil;
import org.spiderflow.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Nicky.Tang on 2020/4/4 9:37 PM
 *
 * @since 02.12.10
 */
@RestController
@RequestMapping("users")
@PermissionCheck
public class UsersController {

    @Autowired
    UsersService usersService;
    @Autowired
    LogsService logsService;
    @Autowired
    RedisUserInfoUtil redisUserInfoUtil;

       @RequestMapping(value = "/register")
    @ResponseBody
    public ResponseResult<String> register(HttpServletRequest request, @RequestBody Users users) throws Exception {
        if (users == null || StringUtils.isEmpty(users.getUserPassword()) || StringUtils.isEmpty(users.getUserPhone())) {
            return RestResultGenerator.genErrorResult("用户名或密码不能为空！！");
        }
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("user_phone", users.getUserPhone());
        List<Users> usersList = (List<Users>) usersService.listByMap(columnMap);
        if (!CollectionUtils.isEmpty(usersList)) {
            return RestResultGenerator.genErrorResult("用户名：【" + users.getUserPhone() + "】 已存在！");
        }
        users.setUserPassword(Md5Utils.getMd5Value(users.getUserPassword()));
        users.setCreateTime(DataUtil.getNow());
        usersService.save(users);
        return RestResultGenerator.genResult("注册成功！");
    }
    @RequestMapping(value = "/login")
    @ResponseBody
    public ResponseResult<Users> login(HttpServletRequest request, @RequestBody Users users) throws Exception {
        if (users == null || StringUtils.isEmpty(users.getUserPassword()) || StringUtils.isEmpty(users.getUserPhone())) {
            return RestResultGenerator.genErrorResult("用户名或密码不能为空！！");
        }
        //1.从数据库中查出用户信息
        List<Users> usersList = usersService.findUserInfo(users.getUserPhone());
        if (CollectionUtils.isEmpty(usersList)) {
            return RestResultGenerator.genErrorResult("请输入正确的用户名或密码！！");
        }
        Users usersDB = usersList.get(0);
        Logs logs = new Logs(usersDB, request);
        logs.setLogsType(Logs.Constant.LogsType.loggin);
        //2.比对加盐加密后的密码
        if (!usersDB.getUserPassword().equals(Md5Utils.getMd5Value(users.getUserPassword()))) {
            logs.setRemarks("密码错误");
            //2.1 记录登陆日志
            logsService.save(logs);
            return RestResultGenerator.genErrorResult("请输入正确的用户名或密码！！");
        }
        //3.如果已经停用，不允许登陆
        if (!ConstantCom.DataStatus.viable.equals(usersDB.getDataStatus())){
            //3.1 记录登陆日志
            logs.setRemarks("账户已停用");
            logsService.save(logs);
            return RestResultGenerator.genErrorResult("账户已停用，请联系管理员！！");
        }
        //4.将用户的个人信息，以及权限信息存入redis，方便后面的调用
        redisUserInfoUtil.initUserInfo(usersDB);
        logs.setRemarks("登陆成功");
        logsService.save(logs);
        return RestResultGenerator.genResult(usersDB, "登陆成功！");
    }

    @RequestMapping(value = "/updateCheckPer")
    @ResponseBody
    @PermissionCheck(perCode = PermissionCodeEnum.jiben)
    public ResponseResult<String> updateCheckPer(HttpServletRequest request) throws Exception {
        return RestResultGenerator.genResult("您有修改权限！");
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    @PermissionCheck(perCode = PermissionCodeEnum.jiben)
    public ResponseResult<Users> update(HttpServletRequest request, @RequestBody UsersUpdate users) throws Exception {
        if (users == null || StringUtils.isEmpty(users.getUserPassword()) || StringUtils.isEmpty(users.getUserPhone()) || StringUtils.isEmpty(users.getUserPasswordOld())) {
            return RestResultGenerator.genErrorResult("用户名或密码不能为空！！");
        }
        Users usersRedis = redisUserInfoUtil.getUserByKey();
        if (usersRedis == null) {
            return RestResultGenerator.genErrorResult("您还未登陆！!");
        }
        if (!usersRedis.getUserPhone().equals(users.getUserPhone())) {
            return RestResultGenerator.genErrorResult("用户名不允许更改！!");
        }
        String oldPassward = Md5Utils.getMd5Value(users.getUserPasswordOld());
        String newPassward = Md5Utils.getMd5Value(users.getUserPassword());
        if (!usersRedis.getUserPassword().equals(oldPassward)) {
            return RestResultGenerator.genErrorResult("请输入正确的原密码！!");
        }
        usersRedis.setUserPassword(newPassward);
        usersRedis.setUserHeaderId(users.getUserHeaderId());
        usersRedis.setUserHeaderUrl(users.getUserHeaderUrl());
        //处理头像
        usersService.updateById(usersRedis);
        redisUserInfoUtil.initUserInfo(usersRedis);
        //记录日志
        Logs logs = new Logs(usersRedis, request);
        logs.setLogsType(Logs.Constant.LogsType.updateUser);
        logs.setRemarks("修改用户信息");
        logsService.save(logs);
        return RestResultGenerator.genResult(usersRedis, "修改成功！");
    }

    @RequestMapping(value = "/logout")
    @ResponseBody
    public ResponseResult<Users> logout(HttpServletRequest request) throws Exception {
        //记录日志
        Users usersRedis = null;
        try {
            usersRedis = redisUserInfoUtil.getUserByKey();

        } catch (ExecptionWhole ex) {
            ex.printStackTrace();
        }
        if (usersRedis == null) {
            return RestResultGenerator.genResult("您还未登陆！");
        }
        Logs logs = new Logs(usersRedis, request);
        logs.setLogsType(Logs.Constant.LogsType.loggin);
        logs.setRemarks("退出登陆");
        logsService.save(logs);
        redisUserInfoUtil.logout();

        return RestResultGenerator.genResult("您已退出登陆！");
    }
}